package com.example.beijing.beijingdemo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;

import com.example.beijing.beijingdemo.R;
import com.example.beijing.beijingdemo.base.BaseActivity;
import com.example.beijing.beijingdemo.util.Constants;
import com.example.beijing.beijingdemo.util.SPUtils;

/**
 * 欢迎界面
 */

public class SplashActivity extends BaseActivity implements Animation.AnimationListener {

    private View mBg;

    private int DURATION_ANIMATION = 500;// 动画时间
    private int DURATION_DELAYED = 500;// 跳转延迟

    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_activity);

        mBg = findViewById(R.id.splash_home);

        Animation animation = createAnimation();

        animation.setAnimationListener(this);

        mBg.startAnimation(animation);
    }

    /**
     * 创建动画
     */
    private Animation createAnimation() {
        AnimationSet set = new AnimationSet(false);
        // 旋转
        RotateAnimation rotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotate.setDuration(DURATION_ANIMATION);
        // 缩放
        ScaleAnimation scale = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scale.setDuration(DURATION_ANIMATION);
        // 透明
        AlphaAnimation alpha = new AlphaAnimation(0, 1);
        alpha.setDuration(DURATION_ANIMATION);

        set.addAnimation(rotate);
        set.addAnimation(scale);
        set.addAnimation(alpha);
        return set;
    }

    @Override
    public void onAnimationStart(Animation animation) {
    }

    @Override
    public void onAnimationEnd(Animation animation) {
        // 延迟两秒进入向导界面
        mHandler.postDelayed(new MyTask(), DURATION_DELAYED);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
    }

    private class MyTask implements Runnable {
        @Override
        public void run() {
            boolean has_guide = SPUtils.getBoolean(SplashActivity.this, Constants.KEY_HAS_GUIDE, false);
            if (has_guide) {
                // 进入主界面
                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                startActivity(intent);
                finish();// 结束
            } else {
                // 进入向导界面
                Intent intent = new Intent(SplashActivity.this, GuildActivity.class);
                startActivity(intent);
                finish();// 结束
            }
        }
    }
}
